import time
import random
import string
import hashlib
from django.core.cache import cache
from django.urls import reverse
from django.template.loader import render_to_string

from mysite.utils import EmailSender

def send_activation_email(request, user, email):
    data = {}
    # 发送间隔确认
    interval_verify = cache.get('activation_{}'.format(user.pk))
    if (interval_verify is not None) and (time.time() - interval_verify['last_send_time'] < 30):
        data['status'] = 'ERROR'
        data['message'] = '两次发送邮件时间过短'
        return data
    # 生成随机验证连接，随机字符串长度为4
    random_str = ''.join(random.sample(string.ascii_letters+string.digits, 4))
    # sha256加密
    random_str = hashlib.sha256(random_str.encode('utf-8')).hexdigest()
    cache_context = {}
    cache_context['email'] = email
    cache_context['captcha'] = random_str
    cache_context['last_send_time'] = int(time.time())
    # 保存到数据库缓存，有效时间为5分钟
    cache.set('activation_{}'.format(user.pk), cache_context, 300)
    print('save cache activation_{}'.format(user.pk))
    # 生成验证连接
    verify_url = request.build_absolute_uri(reverse('activate_user', args=(random_str, user.pk)))
    # 异步发送验证邮件
    context = {}
    context['content'] = '<p>请点击下面连接确认验证，有效时间为5分钟:</p>'
    context['url'] = verify_url
    subject = '邮箱激活'
    message = ''
    html_message = render_to_string('user/verify_content.html', context) 
    email_sender = EmailSender(subject, message, email, html_message)
    email_sender.start()
    data['status'] = 'SUCCESS'
    return data

def send_captcha_email(user, email, prefix):
    '''
    发送验证码到邮箱，需要参数
    user:表示验证用户
    email:邮箱地址
    prefix:缓存前缀
    '''
    data = {}
    cache_key = '{}_{}'.format(prefix, user.pk)
    # 发送间隔确认
    interval_verify = cache.get(cache_key)
    if (interval_verify is not None) and (time.time() - interval_verify['last_send_time'] < 30):
        data['status'] = 'ERROR'
        data['message'] = '两次发送验证码时间过短'
        return data
    # 生成四位随机验证码
    random_captcha = ''.join(random.sample(string.ascii_letters+string.digits, 4))
    cache_context = {}
    cache_context['user'] = user
    cache_context['captcha'] = random_captcha
    cache_context['last_send_time'] = int(time.time())
    # 保存到数据库缓存，有效时间为5分钟
    cache.set(cache_key, cache_context, 300)
    # 异步发送验证邮件
    context = {}
    context['content'] = '<p><span>验证码如下，有效时间为5分钟:<span><span>{}</span></p>'.format(random_captcha)
    context['url'] = ''
    subject = '邮箱验证码'
    message = ''
    html_message = render_to_string('user/verify_content.html', context) 
    email_sender = EmailSender(subject, message, email, html_message)
    email_sender.start()
    data['status'] = 'SUCCESS'
    return data
